package com.sound.controller;

import com.sound.common.ParamCode;
import com.sound.common.QiNiuConfig;
import com.sound.common.Response;
import com.sound.config.WebChinese;
import com.sound.model.UserModel;
import com.sound.service.RedisService;
import com.sound.service.UserService;
import com.sound.utils.CheckUtils;
import com.sound.vo.TypeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@Api(tags="用户")
@RequestMapping(path="/user")
public class UserController extends BaseController<UserModel>{


    @Autowired
    private  static  String  MSG_CODE="msgCode";

    @Autowired
    private UserService userSevice;

    @Autowired
    public QiNiuConfig qiNiuConfig;

    @Resource
    private RedisService redisService;

    @Autowired
    private WebChinese webChinese;


    @Value("${qiniu.sound.download}")
    private  String soundDownload;

    @Value("${qiniu.imgs.download}")
    private  String imgsDsownload;


    private static final Logger logger = LoggerFactory.getLogger(UserController.class);


    /**
     * 登陆接口
     * @param userId
     * @param password
     * @return
     */
    @GetMapping(path="/login.do")
    public Response login(@RequestParam("userId") String userId, @RequestParam("password") String password,HttpServletRequest request, HttpServletResponse response){

        Response resp = new Response();
        try{
            UserModel user =userSevice.findByUserName(userId);
            if(user==null){
                resp.setRespone(ParamCode.FAIL);
                resp.setMsg("用户不存在");
                return resp;
            }
            if(!password.equals(user.getPassword())){
                resp.setRespone(ParamCode.FAIL);
                resp.setMsg("用户名或密码有误");
                return resp;
            }
            String token_st = user.getUserId()+user.getPassword()+ (new Date()).getTime();
            HttpSession session = request.getSession();

            String token = "";
            try {
                token = DigestUtils.md5DigestAsHex(token_st.getBytes("utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            redisService.saveUser(token,user);

//            session.setMaxInactiveInterval(24*3600);
            Cookie cookie = new Cookie("ssoToken",token);
            cookie.setPath("/");
            response.addCookie(cookie);
            response.addCookie(cookie);
            user.setPassword("");
            HashMap<String,Object> result = new HashMap<>();
            result.put("userInfo",user);
            result.put("ssoToken",token);
            resp.setRespone(ParamCode.SUCSESS);
            resp.setData(result);
            return resp;
        }catch (Exception e){
            logger.error("user login fail:",e);
        }
        resp.setRespone(ParamCode.FAIL);
        resp.setMsg("用户名或密码有误");
        return resp;

    }

    /**
     * 头像上传
     * @param file
     * @return
     */
    @PostMapping(path="/uploadhead.do")
    public Response upLoadhead(@RequestParam("file") MultipartFile file,
                               HttpServletRequest request){
        Response resp = new Response();
        UserModel userModel = redisService.getUserInfo(request);
        //验证登陆态
        if(userModel==null||userModel.getId()<=0){
            resp.setRespone(ParamCode.NOLOGIN);
            resp.setMsg("用户请登录！");
            return resp;
        }

        if(file.isEmpty()){
            resp.setRespone(ParamCode.FAIL);
            resp.setMsg("文件为空");
            return resp;
        }
        //上传文件到七牛云
        File file1 = null;
        String key = null;
        try {
            file1 = File.createTempFile(file.getName(),".tmp");
            file.transferTo(file1);
            key= qiNiuConfig.upLoadImg(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(StringUtils.isEmpty(key)){
            resp.setRespone(ParamCode.FAIL);
            resp.setMsg("上传头像失败");
            return resp;
        }
        userModel.setHeaderUrl(key);
        userModel.setHeadFileName(file.getOriginalFilename());
        UserModel resultModel = userSevice.save(userModel);
        resp.setRespone(ParamCode.SUCSESS);
        resultModel.setPassword("");
        resp.setData(resultModel);
        return resp;
    }
    /**
     * 修改昵称
     */
    @PostMapping(path="/changename.do")
    public Response upLoadhead(String name,
                               HttpServletRequest request){
        Response resp = new Response();

        UserModel userModel = redisService.getUserInfo(request);
        if(userModel==null||userModel.getId()<=0){
            resp.setRespone(ParamCode.NOLOGIN);
            resp.setMsg("用户请登录！");
            return resp;
        }

        UserModel user = userSevice.findById(userModel.getId());
        if(user==null || user.getId()<=0){
            resp.setRespone(ParamCode.FAIL);
            resp.setMsg("该用户不存在！");
            return resp;
        }
        if(!CheckUtils.checkName(name)){
            resp.setRespone(ParamCode.FAIL);
            resp.setMsg("请输入2-10位英文或汉字");
            return resp;
        }
        user.setName(name);
        try{
            UserModel resultModel = userSevice.save(user);
            resultModel.setPassword("");
            resp.setRespone(ParamCode.SUCSESS);
            resp.setData(resultModel);
        }catch (Exception e){
            logger.error("modify user name fail:",e);
            resp.setRespone(ParamCode.FAIL);
            resp.setMsg("名称修改失败");
        }
        return resp;
    }

    /**
     * 发送短信码
     * @param userId
     * @return
     */
    @GetMapping(path = "/sendMsg.do")
    public Response sendMsg(String userId,HttpServletRequest request, HttpServletResponse response){

        Response resp = new Response();
        String code = getCode();
        if(code!=null){
            String codeMsg = redisService.getCode(userId);
            if(codeMsg != null){
                resp.setRespone(ParamCode.CODE_IS_ABLE);
                resp.setMsg("验证码有效期中，请10分钟后再发");
                return resp;
            }
            if(webChinese.sendMsg(userId,code)){
                redisService.saveCode(code,userId);
                resp.setRespone(ParamCode.SUCSESS);
                resp.setMsg("发送成功");
                return resp;
            }
        }

        resp.setRespone(ParamCode.FAIL);
        resp.setMsg("短信发送失败");
        return resp;
    }



    @GetMapping(path = "/valitionMsg.do")
    public Response valitionMsg(String userId,String code){
        String codeMsg = null;
        Response resp = new Response(true);
        try {
            codeMsg = redisService.getCode(userId);
            if(code.equals(codeMsg)){
                return resp;
            }
        }catch (Exception e){
            logger.error("valitionMsg fail:",e);
        }
        resp.setRespone(ParamCode.FAIL);
        resp.setMsg("验证码有误");
        return resp;
    }
    /**
     * 注册用户
     * @param userId
     * @param password
     * @return
     */
    @GetMapping(path="/register.do")
    public Response register(@RequestParam("userId")    String userId,
    								@RequestParam("password")  String password,
    								@RequestParam("name")	   String name,
    								@RequestParam("msgCode")    String msgCode,
    								HttpServletRequest request, HttpServletResponse response){

        Response resp =new Response();
        if(!CheckUtils.checkCellphone(userId)){
            resp.setRespone(ParamCode.FAIL);
            resp.setMsg("用户ID不正确");
            return resp;
        }
        if(!CheckUtils.checkPwd(password)){
            resp.setRespone(ParamCode.FAIL);
            resp.setMsg("密码格式不正确");
            return resp;
        }
        if(!CheckUtils.checkName(name)){
            resp.setRespone(ParamCode.FAIL);
            resp.setMsg("用户昵称格式不正确");
            return resp;
        }

        try{
            UserModel user = userSevice.findByUserName(userId);

            if(user != null && user.getId()>0){
                resp.setRespone(ParamCode.FAIL);
                resp.setMsg("用户已经存在！");
                return resp;
            }

            String value = redisService.getCode(userId);

            if(!msgCode.equals(value)){
                resp.setRespone(ParamCode.FAIL);
                resp.setMsg("验证码不正确");
                return resp;
            }
            UserModel us = new UserModel();
            us.setUserId(userId);
            us.setPassword(password);
            us.setName(name);
            UserModel userModel = userSevice.save(us);

            String token_st = userModel.getUserId()+userModel.getPassword()+ (new Date()).getTime();
            HttpSession session = request.getSession();

            String token = "";
            try {
                token = DigestUtils.md5DigestAsHex(token_st.getBytes("utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            redisService.saveUser(token,userModel);

            session.setMaxInactiveInterval(24*3600);
            Cookie cookie = new Cookie("ssoToken",token);
            cookie.setPath("/");
            response.addCookie(cookie);
            response.addCookie(cookie);
            userModel.setPassword("");

            Map<String,Object> map = new HashMap<>();
            map.put("userInfo",userModel);
            map.put("ssoToken",token);
            resp.setData(map);
            resp.setRespone(ParamCode.SUCSESS);
            resp.setMsg("注册成功！");
            return resp;
        }catch (Exception e){
            logger.error("user register fail:",e);
        }
        return new Response(false);
    }

    /**
     * 修改密码
     * @param userId
     * @param password
     * @return
     */
    @GetMapping(path = "/updatePwd.do")
    public Response changePassword(@RequestParam("msgCode") String msgCode,
    									@RequestParam("userId")	  String userId, 
    									@RequestParam("password") String password,
    									HttpServletRequest request, HttpServletResponse rep){

        Response resp =new Response();
//        UserModel userModel = redisService.getUserInfo(request);
//
//        if(userModel==null || userModel.getId()<=0){
//            resp.setRespone(ParamCode.FAIL);
//            resp.setMsg("该用户不存在！");
//            return resp;
//        }
        String msgcode = redisService.getCode(userId);
        if(!msgCode.equals(msgcode)){
            resp.setRespone(ParamCode.FAIL);
            resp.setMsg("验证码不正确");
            return resp;
        }
        if(!CheckUtils.checkPwd(password)){
            resp.setRespone(ParamCode.FAIL);
            resp.setMsg("密码格式不正确");
            return resp;
        }
        UserModel mo =userSevice.findByUserName(userId);
        if(mo==null) {
        	 	resp.setRespone(ParamCode.FAIL);
        	 	resp.setMsg("该用户不存在！");
        	 	return resp;
        }
        mo.setPassword(password);
        userSevice.save(mo);
        resp.setRespone(ParamCode.SUCSESS);
        resp.setMsg("修改成功");
        return resp;
    }


    private static String getCode() {
        String res = "";
        Random r = new Random();
        for(int i=0;i<6;i++){
            int m =0 + r.nextInt(9 - 0);
            res=res+m;
        }

        return res;
    }


    @GetMapping(path="/hostUrl.do")
    @ApiOperation(value = "获取域名地址",tags = "",response = TypeVo.class)
    public Response getList(){
        Response resp = new Response();
        Map<String ,String> map  = new HashMap<>();
        map.put("audiohost",soundDownload);
        map.put("imghost",imgsDsownload);
        resp.setData(map);
        resp.setRespone(ParamCode.SUCSESS);
        return resp;

    }

    @GetMapping(path = "/loginout.do")
    @ApiOperation(value = "退出登录",tags = "",response = Boolean.class)
    public Response loginOut(HttpServletRequest request){
        Response resp = new Response(true);
        try{
            UserModel userModel = redisService.getUserInfo(request);
            if(userModel != null||userModel.getId()>0){
                redisService.loginout(userModel.getUserId());
            }
        }catch (Exception e){
            logger.info("login out exception",e);
        }
        return resp;
    }
}
